package com.yiyaOvo.cloudDisk.utils;

import com.alibaba.fastjson.JSON;
import com.yiyaOvo.cloudDisk.pojo.FileItem;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * User: yiyaOvo
 * Date: 2021/5/23
 * Time: 14:33
 * role: 文件工具类
 */
public class FileUtils {

    // 服务器IP地址
    public static final String IP = "127.0.0.1";
    // 服务器端口
    public static final int PORT = 8888;
    // 上传文件路径
    public static final String UPLOAD_DIR = "D:\\workspace\\cloudDisk\\upload";
    // 下载文件路径
    public static final String DOWNLOAD_DIR = "D:\\workspace\\cloudDisk\\download";
    //  type the command
    public static final int TYPE_LOGIN = 1;
    public static final int TYPE_LIST = 2;
    public static final int TYPE_UPLOAD = 3;
    public static final int TYPE_DOWNLOAD = 4;
    public static final int TYPE_DELETE = 5;


    /**
     * 获得上传文件列表
     * @return
     */
    public static List<FileItem> getUploadFiles () {
        File file = new File(UPLOAD_DIR);
        if (!file.exists()) {
            file.mkdirs();
            return null;
        }

        File[] files = file.listFiles();
        // 将文件信息添加到List集合中
        List<FileItem> fileItemList = new ArrayList<>();
        for (int i = 0; i < files.length; i ++) {
            File f = files[i];
            if (f.isFile()) {
                FileItem fileItem = new FileItem(i + 1L, f.getName(), f.getAbsolutePath(), f.length());
                fileItemList.add(fileItem);
            }
        }
        return fileItemList;
    }

    /**
     * file IO
     * @param in
     * @param out
     */
    public static void io (InputStream in, OutputStream out) throws IOException {
        byte[] buff = new byte[1024];
        int len = 0;
        // read subsections from the input stream
        while ((len = in.read(buff)) != -1) {
            // write subsections to output stream
            out.write(buff, 0, len);
        }
        in.close();
        out.close();
    }


    /**
     * 将List集合转化为JSON
     * @param fileItems
     * @return
     */
    public static String listToJSON (List<FileItem> fileItems) {
        return JSON.toJSONString(fileItems);
    }

    /**
     * 将json字符串转化为List集合
     * @param json
     * @return
     */
    public static List<FileItem> jsonToList (String json) {
        return JSON.parseArray(json, FileItem.class);
    }

    public static void main(String[] args) {
        List<FileItem> uploadFiles = getUploadFiles();
        String json = listToJSON(uploadFiles);
        System.out.println(json);
        List<FileItem> fileItemList = jsonToList(json);
        System.out.println("-------------");
        System.out.println(fileItemList);
    }
}
